#include "PlayerManager.h"

PlayerManager::PlayerManager()
{
	//ctor
}

PlayerManager::~PlayerManager()
{
	//dtor
}

bool PlayerManager::Init(Database& _pDB)
{
	m_pDB = &_pDB;
	return true;
}

Player* PlayerManager::GetPlayer(int _Playerid)
{
	if(m_DataMap.count(_Playerid) != 0)
	{
		return &m_DataMap[_Playerid];
	}

	// 如果没有 可能是登录后第一次查询
	tPlayer* pDBPlayer = m_pDB->SelectPlayer(_Playerid);
    if(pDBPlayer != nullptr)
	{
		this-> Cache(*pDBPlayer);
		return &m_DataMap[_Playerid];
	}

    return nullptr;
}


Player* PlayerManager::GetPlayerByFd(int _fd)
{
	if(m_fdIDMap.count(_fd) != 0)
	{
		return GetPlayer(m_fdIDMap[_fd]);
	}

	return nullptr;
}

int PlayerManager::GetPlayerId(int _userId)
{
	if(m_userIdPlayerIdMap.count(_userId) > 0)
		return m_userIdPlayerIdMap[_userId];

	// 如果缓存没有 则向数据库中查询
    tPlayer* pDBPlayer = m_pDB->SelectPlayerByUserId(_userId);
    if(pDBPlayer == nullptr)
	{
		return -1;
	}

	m_userIdPlayerIdMap[_userId] = pDBPlayer->id;
	return m_userIdPlayerIdMap[_userId];
}

bool PlayerManager::isExist(int _userId)
{
	int playerId = _userId;

	// 如果内存中已经有了
	if(m_DataMap.count(playerId) > 0)
		return true;

	// 如果数据库中已经有了
	if(m_pDB->IsExistPlayer(playerId))
		return true;

	return false;
}

// -1 错误 -2已经创建 -3角色创建错误
int PlayerManager::Create(int _userId, int _roleCfgId, string _name, RoleManager* _pRoleMgr, GlobalManager* _pGlobalMgr)
{
	// 如果帐号已经存在
	if(isExist(_userId))
		return -2;

	// 创建一个角色
	int roleId = _pRoleMgr->Create(_roleCfgId, _name, _pGlobalMgr);
	if( roleId < 0)
	{
		Debug::Error(__func__, " roleId < 0, roleId:", roleId);
		return -3;
	}

	// 创建一个玩家
	int newId = _userId;
	tPlayer newT;
	newT.id = newId;
	newT.userId = newId;
	newT.sex = 0;
	newT.silver = 0;
	newT.gold = 0;
	newT.diamond = 0;
	newT.birthtime = 0;
	newT.name = _name;
	newT.desc = "无";
	newT.roleId = roleId;
	newT.aryId = 0;

	if( m_pDB->InsertPlayer(newT) )
	{
		return -1;
	}

	// 缓存
	this->Cache(newT);

	return newId;
}

bool PlayerManager::Cache(const tPlayer& _DB)
{
	if(m_DataMap.count(_DB.id) > 0)
	{
		Debug::Error(__func__, " Alreay in PlayerManager Cache _DB.id:", _DB.id);
		return false;
	}

	Player Data;
	Data.m_oid = _DB.id;
	Data.m_uid = _DB.userId;
	Data.m_sex = _DB.sex;
	Data.m_silver = _DB.silver;
	Data.m_gold = _DB.gold;
	Data.m_diamond = _DB.diamond;
	Data.m_birthtime = _DB.birthtime;
	Data.m_name = _DB.name;
	Data.m_desc = _DB.desc;
	Data.m_roleId = _DB.roleId;
	Data.m_aryId = _DB.aryId;

	m_DataMap[Data.m_oid] = Data;
	return true;
}

